package com.solweaver.greetings.controller;

import java.util.Calendar;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.brickred.socialauth.AuthProvider;
import org.brickred.socialauth.Permission;
import org.brickred.socialauth.Profile;
import org.brickred.socialauth.SocialAuthConfig;
import org.brickred.socialauth.SocialAuthManager;
import org.brickred.socialauth.spring.bean.SocialAuthTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.solweaver.greetings.dto.EmailMessage;
import com.solweaver.greetings.dto.EventCreationRequest;
import com.solweaver.greetings.dto.EventCreationResponse;
import com.solweaver.greetings.dto.GetEventsByUserRequest;
import com.solweaver.greetings.dto.GetEventsByUserResponse;
import com.solweaver.greetings.dto.GetUsersByEventRequest;
import com.solweaver.greetings.dto.GetUsersByEventResponse;
import com.solweaver.greetings.dto.ModifyEventRequest;
import com.solweaver.greetings.dto.ModifyEventResponse;
import com.solweaver.greetings.dto.UserDTO;
import com.solweaver.greetings.dto.UserMetaDataDTO;
import com.solweaver.greetings.dto.UserResponse;
import com.solweaver.greetings.dto.VideoRecordingRequest;
import com.solweaver.greetings.dto.VideoRecordingResponse;
import com.solweaver.greetings.service.IEventService;
import com.solweaver.greetings.service.IUserService;
import com.solweaver.greetings.utils.GenericUtils;
import com.solweaver.greetings.utils.JmsUtils;
import com.solweaver.greetings.utils.NotificationUtils;
import com.solweaver.greetings.utils.ValidationUtils;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {

	@Autowired
	private SocialAuthTemplate socialAuthTemplate;
	
	@Autowired
	private IUserService userService;
	
	@Autowired
	private IEventService eventService;

	@Resource(name="notificationJmsTemplate")
	@Autowired
	private JmsTemplate notificationJmsTemplate;
	
	private static final Logger LOGGER = LoggerFactory
			.getLogger(HomeController.class);

	@RequestMapping(value = "/home")
	public String hello(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		LOGGER.info("In Hello World Method");
		return "index";
	}
	
	@RequestMapping(value = "/main")
	public String MainApp(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		LOGGER.info("In main app");
		return "main";
	}

	@RequestMapping(value = "/authSuccess")
	public String authSuccess(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		LOGGER.info("In Login");

		SocialAuthConfig config = SocialAuthConfig.getDefault();
		
		request.getSession().removeAttribute("userProfile");
		
		SocialAuthManager manager = socialAuthTemplate.getSocialAuthManager();
        AuthProvider provider = manager.getCurrentAuthProvider();
		//AuthProvider provider = AuthProviderFactory.getInstance("google");
		
		provider.setPermission(Permission.ALL);
		//provider.getLoginRedirectURL("http://greetings.solweaver.com:8080/Greetings/authSuccess");
		Profile userProfile = provider.getUserProfile();
		request.getSession().setAttribute("userProfile", userProfile);
		
		UserDTO userDTO = new UserDTO();
		userDTO.setEmailId(userProfile.getEmail());
		userDTO.setFirstName(userProfile.getFirstName());
		userDTO.setLastName(userProfile.getLastName());

		UserMetaDataDTO userMetaDataDTO = new UserMetaDataDTO();
		userMetaDataDTO.setLastLoggedInDeviceId(request.getLocalAddr());
		userMetaDataDTO.setLastLoggedInTime(Calendar.getInstance().getTime());
		userMetaDataDTO.setProviderId(userProfile.getProviderId());
		userMetaDataDTO.setRegisteredDeviceId(request.getLocalAddr());
		UserResponse userResponse = userService.createUserIfNotExists(userDTO, userMetaDataDTO);
		return "index";
	}
	
	@RequestMapping(value = "/authFailure")
	public String authFailure(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		LOGGER.info("In Login Failure");
		
		return "index";
	}
	

/*	@RequestMapping(value="/createEvent1", method=RequestMethod.POST)
	public @ResponseBody EventCreationRequest createEvent1(){
	
		EventCreationRequest eventCreationRequest = new EventCreationRequest();
		eventCreationRequest.setDescription("Test");
		eventCreationRequest.setChannel(Channel.ANDROID);
		eventCreationRequest.setFromMessage("Testing mesg");
		eventCreationRequest.setEventDate(new Timestamp(Calendar.getInstance().getTimeInMillis()));
		return eventCreationRequest;
	}*/
	
	/*@RequestMapping(value="/getEvents1", method=RequestMethod.POST)
	public @ResponseBody GetEventsRequest createEvent1(){
	
		GetEventsRequest getEventsRequest = new GetEventsRequest();
		getEventsRequest.setEventStatus(EventStatus.Active);
		List<UserEventType> userEventTypeList = new ArrayList<UserEventType>();
		userEventTypeList.add(UserEventType.All);
		getEventsRequest.setUserEventTypeList(userEventTypeList);
		getEventsRequest.setChannel(Channel.WEB);
		getEventsRequest.setUserId(1l);
		return getEventsRequest;
	}*/
	
	@RequestMapping(value="/createEvent", method=RequestMethod.POST)
	public @ResponseBody EventCreationResponse createEvent(@RequestBody EventCreationRequest eventCreationRequest){
		LOGGER.info("In Login Failure");
		
		EventCreationResponse eventCreationResponse = new EventCreationResponse();
		
		ValidationUtils.validateEventCreationRequest(eventCreationResponse, eventCreationRequest);
		
		if(GenericUtils.isSuccess(eventCreationResponse.getErrorDetailList())){
			eventCreationResponse = eventService.createEvent(eventCreationRequest);
			if(GenericUtils.isSuccess(eventCreationResponse.getErrorDetailList())){
				EmailMessage createdByMessage = NotificationUtils.buildEmailMessage("admin@solweaver.com", eventCreationRequest.getCreatedByUser().getEmailId(),
						"Your greeting Invite is successfully created", "Congratulations!!!!! Your greeting invite is created");
				JmsUtils.sendJmsMessage(createdByMessage, notificationJmsTemplate);
				
				for(UserDTO userDTO : eventCreationRequest.getInviteeList()){
					EmailMessage inviteeMessage = NotificationUtils.buildEmailMessage("admin@solweaver.com", userDTO.getEmailId(),
							"You received a greeting Invite from xxxxxxxx", "You received an invite from xxxxxx. You can upload your greeting @ xxxxxx");
					JmsUtils.sendJmsMessage(inviteeMessage, notificationJmsTemplate);
				}
			}
		}else{
			return eventCreationResponse;
		}
		
		return eventCreationResponse;
	}
	
	@RequestMapping(value="/modifyEvent", method=RequestMethod.POST)
	public @ResponseBody ModifyEventResponse modifyEvent(@RequestBody ModifyEventRequest modifyEventRequest){
		LOGGER.info("In Login Failure");
		
		ModifyEventResponse modifyEventResponse = new ModifyEventResponse();
		
		ValidationUtils.validateModifyEventRequest(modifyEventResponse, modifyEventRequest);
		
		if(GenericUtils.isSuccess(modifyEventResponse.getErrorDetailList())){
			modifyEventResponse = eventService.modifyEvent(modifyEventRequest);
			if(GenericUtils.isSuccess(modifyEventResponse.getErrorDetailList())){
				//TODO - Base on modifyEventResponse.getUpdatedFields(), necessary email templates should be used
			}
		}else{
			return modifyEventResponse;
		}
		
		return modifyEventResponse;
	}
	
	@RequestMapping(value="/getEventsByUser", method=RequestMethod.POST)
	public @ResponseBody GetEventsByUserResponse getEventsByUser(@RequestBody GetEventsByUserRequest getEventsByUserRequest){
		GetEventsByUserResponse getEventsByUserResponse = new GetEventsByUserResponse();
		
		ValidationUtils.validateGetEventsByUserRequest(getEventsByUserRequest, getEventsByUserResponse);
		
		if(GenericUtils.isSuccess(getEventsByUserResponse.getErrorDetailList())){
			getEventsByUserResponse = eventService.findEventsByUserId(getEventsByUserRequest);		
		}
		
		return getEventsByUserResponse;
	}
	
	@RequestMapping(value="/getUsersByEvent", method=RequestMethod.POST)
	public @ResponseBody GetUsersByEventResponse getUsersByEvent(@RequestBody GetUsersByEventRequest getUsersByEventRequest){
		GetUsersByEventResponse getUsersByEventResponse = new GetUsersByEventResponse();
		
		ValidationUtils.validateGetUsersByEventRequest(getUsersByEventRequest, getUsersByEventResponse);
		
		if(GenericUtils.isSuccess(getUsersByEventResponse.getErrorDetailList())){
			getUsersByEventResponse = eventService.findUsersByEvent(getUsersByEventRequest);		
		}
		
		return getUsersByEventResponse;
	}
	
	@RequestMapping(value="/recording", method=RequestMethod.POST)
	public @ResponseBody VideoRecordingResponse record(@RequestBody VideoRecordingRequest videoRecordingRequest){
		
		VideoRecordingResponse videoRecordingResponse = new VideoRecordingResponse();
		
		ValidationUtils.validateRecordingRequest(videoRecordingResponse, videoRecordingRequest);
		
		if(GenericUtils.isSuccess(videoRecordingResponse.getErrorDetailList())){
			videoRecordingResponse = eventService.record(videoRecordingRequest);		
		}
		
		return videoRecordingResponse;
	}
	
	
}
